package com.servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.model.User;
import com.repository.UserRepositoryImpl;
import com.service.UserService;
import com.service.UserServiceImpl;

@WebServlet("/UserRegisterServlet")
public class UserRegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public UserRegisterServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("WEB-INF/views/register.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		System.out.println(username);
		String password = request.getParameter("password1");
		System.out.println(password);
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		
		String msg = null;
		UserServiceImpl userservice;
		try {
			userservice = new UserServiceImpl();
			System.out.println(user);
			if (userservice.userRegister(user)) {
				msg = "注册成功";
				request.setAttribute("msg", msg);
				request.getRequestDispatcher("WEB-INF/views/login.jsp").forward(request, response);
			} else {
				msg = "用户已存在";
				request.setAttribute("msg", msg);
				request.getRequestDispatcher("index.jsp").forward(request, response);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
